package com.gitee.socket.component;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.gitee.socket.domain.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.UUID;

/**
 * @author : cc
 * @date : Create in 16:58 2018/8/23
 */
@Component
@Slf4j
public class MessageEventHandle {
    public final SocketIOServer socketIoServer;
    private static ArrayList<UUID> listClient = new ArrayList<>();
    private static final int limitSeconds = 60;

    @Autowired
    public MessageEventHandle(SocketIOServer server) {
        this.socketIoServer = server;
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        String clientId = client.getHandshakeData().getSingleUrlParam("clientId");
        listClient.add(client.getSessionId());
        log.info("clientId={}",clientId);
        log.info("客户端:" + client.getSessionId() + "已连接");
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        listClient.removeIf(next -> next.toString().equals(client.getSessionId().toString()));
        log.info("客户端:" + client.getSessionId() + "断开连接");
    }


    @OnEvent(value = "messageevent")
    public void onEvent(SocketIOClient client, AckRequest request, Message data) {
        log.info("发来消息：" + data.getContent());
        socketIoServer.getClient(client.getSessionId()).sendEvent("messageevent", "back data");
    }

    //故障推送
    public void sendBuyLogEvent(String recordId) {   //这里就是向客户端推消息了
        for (UUID clientId : listClient) {
            if (socketIoServer.getClient(clientId) == null) {continue;}
            socketIoServer.getClient(clientId).sendEvent("enewbuy", recordId);
        }
    }

}
